package com.yipao.admin.web.dev;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.yipao.admin.service.LbsTableService;
import com.yipao.admin.service.dev.AdminDevInfoService;
import com.yipao.admin.vo.excel.ExportDevMaintainVo;
import com.yipao.core.util.DateTimeUtil;
import com.yipao.core.util.ResponseUtil;
import com.yipao.core.validator.Order;
import com.yipao.core.validator.Sort;
import com.yipao.db.domain.devinfo.DevInfo;
import com.yipao.db.domain.excel.ExportDevInfoVo;
import com.yipao.db.service.devinfo.DevInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 设备类( 设备信息,设备维护,设备数据)
 *
 * @author like
 */
@RestController
@Validated
@RequestMapping("/admin/devInfo")
public class AdminDevInfoController {
    private final Log logger = LogFactory.getLog(AdminDevInfoController.class);

    @Resource
    private DevInfoService devInfoService;
    @Resource
    private AdminDevInfoService adminDevInfoService;

    /**
     * 新增一条设备记录
     *
     * @param devInfo
     */
    @PostMapping("/add")
    public Object add(@RequestBody DevInfo devInfo) {
        if (devInfo == null ||
                StringUtils.isBlank(devInfo.getScenes()) ||
                StringUtils.isBlank(devInfo.getImei())) {
            return ResponseUtil.fail(402, "参数错误");
        }

        return adminDevInfoService.insert(devInfo);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public Object findById(@PathVariable("id") Integer id) {
        DevInfo devInfo = devInfoService.selectByPrimaryKey(id);
        return ResponseUtil.ok(devInfo);
    }

    /**
     * 更新
     *
     * @param devInfo
     */
    @PostMapping("/update")
    public Object update(@RequestBody DevInfo devInfo) {
        if (devInfo == null || devInfo.getId() == null) {
            return ResponseUtil.fail(402, "参数必填");
        }
        return adminDevInfoService.update(devInfo);
    }

    /**
     * 根据ID删除
     *
     * @param id
     */
    @DeleteMapping("/delete/{id}")
    public Object delete(@PathVariable("id") Integer id) {
        return adminDevInfoService.delete(id);
    }

    /**
     * 多条记录删除
     *
     * @param ids
     */
    @PostMapping("/deleteIds")
    public Object deleteIds(@RequestParam("ids[]") Integer[] ids) {
        return adminDevInfoService.deleteIds(ids);
    }

    /**
     * 根据条件查询
     *
     * @param
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @GetMapping("/selectByExample")
    public Object selectByExample(@RequestParam(value = "devId", required = false) String devId,
                                  @RequestParam(value = "title", required = false) String title,
                                  @RequestParam(value = "employee", required = false) String employee,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer limit,
                                  @Sort @RequestParam(defaultValue = "add_time") String sort,
                                  @Order @RequestParam(defaultValue = "desc") String order) {
        return ResponseUtil.ok(devInfoService.selectByExample(devId, title, employee, page, limit, sort, order));
    }

    /**
     * 获取所有故障码(去重)
     *
     * @return
     */
    @GetMapping("/getStatusCode")
    public Object getAllStatusCode() {
        return ResponseUtil.ok(devInfoService.getAllStatusCode());
    }


    /**
     * 获取所有机器故障状态(去重)
     *
     * @return
     */
    @GetMapping("/getDevStatus")
    public Object getAllDevStatus() {
        return ResponseUtil.ok(devInfoService.getAllDevStatus());
    }


    /**
     * 新增设备
     *
     * @param devInfo
     */
    @PostMapping("/insert")
    public Object insert(DevInfo devInfo) {
        /*devInfo.setAddTime(LocalDateTime.now() + "");
        devInfo.setUpdateTime(LocalDateTime.now() + "");
        devInfoService.insert(devInfo);
        return ResponseUtil.ok();*/

        return this.add(devInfo);
    }

    /**
     * 查询所有
     * @param devId 设备编号
     * @return
     */
    @GetMapping("/findAll")
    public Object findAll(@RequestParam(value = "devStatus", required = false) String devStatus,
                          @RequestParam(value = "statusCode", required = false) String statusCode,
                          @RequestParam(value = "title", required = false) String scenes,
                          @RequestParam(value = "devId",required = false) String devId,
                          @RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer limit,
                          @Sort @RequestParam(defaultValue = "add_time") String sort,
                          @Order @RequestParam(defaultValue = "desc") String order,
                          @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date start,
                          @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date end
    ) {
        List<DevInfo> all = devInfoService.findAll(devStatus, statusCode, scenes, devId, start, end, page, limit, sort, order);
        return ResponseUtil.okList(all);
    }

    /**
     * 根据时间查询
     *
     * @param start 开始时间
     * @param end   截止时间
     * @return
     */
    @GetMapping("/selectByTime")
    public Object selectByTime(@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
                               @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {

        List<DevInfo> byTime = devInfoService.getByTime(start, end);
        return ResponseUtil.ok(byTime);
    }

    /**
     * 导出设备维护的excel
     *
     * @return
     */
    @GetMapping("/export/maintain")
    public void exportDevMaintain(HttpServletResponse response) {


        List<ExportDevInfoVo> list = new ArrayList<>();

        List<ExportDevInfoVo> allExcel = devInfoService.findAllExcel();
        for (ExportDevInfoVo exportDevInfoVo : allExcel) {
            list.add(new ExportDevInfoVo(exportDevInfoVo.getId(),
                    exportDevInfoVo.getDevId(),
                    exportDevInfoVo.getScenes(),
                    exportDevInfoVo.getDevOnline(),
                    exportDevInfoVo.getDevStatus(),
                    exportDevInfoVo.getMaterialStatus(),
                    exportDevInfoVo.getEmployee(),
                    exportDevInfoVo.getPhone(),
                    exportDevInfoVo.getAddress(),
                    exportDevInfoVo.getImei(),
                    exportDevInfoVo.getHappenedTime(),
                    exportDevInfoVo.getCause(),
                    exportDevInfoVo.getStatusCode(),
                    exportDevInfoVo.getInternetNumb()
            ));
        }
        try {
            // 这里注意 使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
            String fileName = URLEncoder.encode("设备维护" + DateTimeUtil.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExportDevMaintainVo.class)
                    // 自动列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("设备维护").doWrite(list);
        } catch (IOException e) {
            logger.error("exportDevMaintain", e);
        }
    }

}
